<?php
/**
 *
 * User: dxk <duxiaokong@sina.com>
 * Date: 2023/4/13 20:27
 */
namespace App\Library\Service\AliCloud;

use OSS\OssClient;

class OSS
{
    private $OSSClient;
    private $bucket = '';
    private $prefix = '';
    private $public_domain = '';

    public function __construct()
    {
        $accessKeyId = config('sys.aliyun.accessKeyId');
        $accessKeySecret = config('sys.aliyun.accessSecret');
        $endpoint = config('sys.aliyun.oss_endpoint');
        $this->bucket = config('sys.aliyun.oss_bucket');
        $this->public_domain = config('sys.aliyun.oss_public_domain');
        $this->OSSClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        if (is_online()) {
            $this->prefix = 'health/prod';
        } else {
            $this->prefix = 'health/dev';
        }
    }

    public function getFilePath($file_name): string
    {
        return $this->public_domain . '/' . $this->prefix . '/' . $file_name;
    }

    /**
     * 删除文件
     * @param $file_name
     * @return array
     */
    public function deleteFile($file_name): array
    {
        try {
            $res = $this->OSSClient->deleteObject($this->bucket, $this->prefix . '/' . $file_name);
            easy_log('aliyun_oss', ['bucket' => $this->bucket, 'action' => 'deleteFile', 'file_name' => $file_name, 'res' => $res]);
            return alert_info(0, "删除成功", ['res' => $res]);
        } catch (\Exception $e) {
            return alert_info(1, $e->getMessage());
        }
    }

    /**
     * 上传文件
     * @param $file_name
     * @param $file_content
     * @return array
     */
    public function uploadFile($file_name, $file_content): array
    {
        try {
            $res = $this->OSSClient->putObject($this->bucket, $this->prefix . '/' . $file_name, $file_content);
            easy_log('aliyun_oss', ['bucket' => $this->bucket, 'action' => 'upload_file', 'file_name' => $file_name, 'res' => $res]);
            if ($res['info']['url']) {
                return alert_info(0, "上传成功", $res);
            } else {
                return alert_info(1, "上传失败", ['res' => $res]);
            }
        } catch (\Exception $e) {
            return alert_info(1, $e->getMessage());
        }
    }
}
